using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Xml.Serialization;
using T4UtilityBelt.DataDesigns.SharePoint;

namespace T4UtilityBelt.DataDesigns
{
    public class PropertyCollection : ObservableCollection<Property>
    {
        public PropertyCollection(Entity entity)
        {
            _propertiesByName = new Dictionary<string, Property>();
            Entity = entity;
        }

        public Entity Entity { get; internal set; }

        private readonly Dictionary<string, Property> _propertiesByName;

        public Property this[string index]
        {
            get
            {
                return _propertiesByName[index];
            }
        }

        protected override void ClearItems()
        {
            base.ClearItems();
            _propertiesByName.Clear();
        }

        protected override void RemoveItem(int index)
        {
            Property item = this[index];
            _propertiesByName.Remove(item.Name);
            base.RemoveItem(index);
        }

        protected override void InsertItem(int index, Property item)
        {
            item.Entity = Entity;
            if (_propertiesByName.ContainsKey(item.Name))
            {
                throw new DuplicateKeyException("Property with this name was already added:" + item.Name);
            }
           _propertiesByName.Add(item.Name, item);
            base.InsertItem(index, item);
        }

        protected override void SetItem(int index, Property item)
        {
            item.Entity = Entity;
            if (_propertiesByName.ContainsKey(item.Name))
            {
                throw new DuplicateKeyException("Property with this name was already added:" + item.Name);
            }
            _propertiesByName.Add(item.Name, item);
            base.SetItem(index, item);
        }
    }
}